package tw.cuttle.view;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import tw.cuttle.CuttleContext;
import tw.cuttle.process.EvaluateViewSupport;

public class JspSupport extends EvaluateViewSupport{
    private Log LOGGER=LogFactory.getLog(JspSupport.class);
    @Override
    protected String evaluate(String view) {
	String content = null;
	String fullUrl = null;
	
	String uri = view;
	if(view.indexOf("?")>=0){
	    uri=view.substring(0, view.indexOf("?"));
	}
	String surfix=null;
	if (uri.indexOf(".") > 0) {
	    surfix = uri.substring(uri.indexOf(".") + 1, uri.length());
	}
	if (view!=null && surfix != null && !surfix.equals("htm") && !surfix.equals("html") && !surfix.equals("jsp")) {
	    try {
		BufferedReader br = null;
		fullUrl = "http://localhost:" + CuttleContext.getActionContext().getActionHelper().getRequest().getServerPort()
			+ CuttleContext.getActionContext().getActionHelper().getRequest().getContextPath() + view;

		URL oURL = new URL(new String(fullUrl));

		br = new BufferedReader(new InputStreamReader(oURL.openStream(), "UTF-8"));
		String line = "";
		StringBuffer requestString = new StringBuffer("");
		while ((line = br.readLine()) != null)
		    requestString.append(line);
		content = requestString.toString();
		br.close();
	    } catch (Exception e) {
		LOGGER.warn(" load url failed!! url:" + fullUrl);
		e.printStackTrace();
	    }

	} else {
	    try {
	    	LOGGER.warn("actionContext:"+CuttleContext.getActionContext());
	    	LOGGER.warn("actionHelper:"+CuttleContext.getActionContext().getActionHelper());
	    	LOGGER.warn("context:"+CuttleContext.getActionContext().getActionHelper().getContext());
		RequestDispatcher rd = CuttleContext.getActionContext().getActionHelper().getContext().getRequestDispatcher(view);
		ImportResponseWrapper irw = new ImportResponseWrapper((HttpServletResponse) CuttleContext.getActionContext().getActionHelper().getResponse());
		rd.include(CuttleContext.getActionContext().getActionHelper().getRequest(), irw);

		content = irw.getString();
	    } catch (Exception e) {
	    	e.printStackTrace();
		LOGGER.error("evalute jsp failed!! url:" + view+";"+e.getMessage());
	    }
	}
	return content;
    }

}
